package com.toptime.cloudhelper.consumer;

import jakarta.annotation.Resource;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaConsumerConfig {

    @Resource
    private KafkaConsumerProps kafkaConsumerProps;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConsumerProps.getBootstrapServers());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConsumerProps.getGroupId());
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, kafkaConsumerProps.getKeyDeserializer());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, kafkaConsumerProps.getValueDeserializer());
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConsumerProps.isEnableAutoCommit());
        props.put("topic", kafkaConsumerProps.getTopic());
//        props.put("auto.commit.interval.ms", "30000");
//        props.put("session.timeout.ms", "130000");
//        props.put("auto.offset.reset", "earliest");
//        props.put("max.poll.interval.ms", "120000");
//        props.put("heartbeat.interval.ms", "5000");
        props.put("security.protocol", "sasl_ssl");
        props.put("sasl.mechanism", "PLAIN");
//        props.put("sasl_ssl.username", kafkaConsumerProps.getProject());
//        props.put("sasl_ssl.password", kafkaConsumerProps.getAccessKey() + "#" + kafkaConsumerProps.getAccessSecret());
        props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\""
                + kafkaConsumerProps.getProject() + "\" password=\"" + kafkaConsumerProps.getAccessKey()
                + "#" + kafkaConsumerProps.getAccessSecret() + "\";");
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }
}
